# coding: utf-8
from PIL import ImageGrab
import numpy as np
import os
import cv2
import sys
import time
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from widgets.time_tip import TimeTip
# fps = 20
# start = 3  # 延时录制
# end = 15  # 自动结束时间
#
# curScreen = ImageGrab.grab()  # 获取屏幕对象
# height, width = curScreen.size
#
# video = cv2.VideoWriter('video02.mp4', cv2.VideoWriter_fourcc('M', 'P', '4', '2'), fps, (height, width))
#
# imageNum = 0
# while True:
#     imageNum += 1
#     captureImage = ImageGrab.grab()  # 抓取屏幕
#     frame = cv2.cvtColor(np.array(captureImage), cv2.COLOR_RGB2BGR)
#
#     #
#     mz_img=cv2.imread('mz.jpg')
#     s_mz_img=cv2.resize(mz_img,(20,20))
#     cv2.imshow('mz_cv', s_mz_img)#,np.zeros((1, 255), np.uint8)
#
#     # 控制窗口显示位置，方便通过按键方式退出
#     cv2.moveWindow('capturing', height - 100, width - 100)
#     if imageNum > fps * start:
#         video.write(frame)
#
#     # 退出条件
#     if cv2.waitKey(50) == ord('q') or imageNum > fps * end:
#         break
# video.release()
# cv2.destroyAllWindows()

class CaptureThread(QThread):

    def __init__(self):
        super(CaptureThread, self).__init__()
        self.fps=30
        self.v_path=''
        self.stop=False
        self._pause=False

    def setting(self,fps,v_path):
        self.fps=fps
        self.v_path=v_path

    def setPause(self,isPause):
        self._pause=isPause

    def _stop(self):
        self.stop=True

    def run(self):
        print('run')
        # fps = 20
        start = 3.8  # 延时录制
        # end = 15  # 自动结束时间
        curScreen = ImageGrab.grab()  # 获取屏幕对象
        height, width = curScreen.size
        self.video = cv2.VideoWriter(self.v_path, cv2.VideoWriter_fourcc('M', 'P', '4', '2'), self.fps, (height, width))##'M', 'P', '4', '2'#*'XVID'#'D', 'I', 'V', '3'

        imageNum = 0
        while self.stop==False:
            # if imageNum > self.fps * start:
            if self._pause==False:
                # self.sleep(1000.0/self.fps)

                imageNum += 1
                print(imageNum)
                captureImage = ImageGrab.grab()  # 抓取屏幕
                frame = cv2.cvtColor(np.array(captureImage), cv2.COLOR_RGB2BGR)
                #
                # mz_img=cv2.imread('mz.jpg')
                # s_mz_img=cv2.resize(mz_img,(20,20))
                # cv2.imshow('录制中',np.zeros((1, 255), np.uint8))#,np.zeros((1, 255), np.uint8)#, s_mz_img

                # 控制窗口显示位置，方便通过按键方式退出
                # cv2.moveWindow('录制中', height - 100, width - 100)
                time.sleep(1.0 / self.fps)
                self.video.write(frame)
                if self.stop==True:
                    break
                # if imageNum >120:
                #     self.video.release()
                #     cv2.destroyAllWindows()
                else:
                    pass
            # else:
            #     pass
            # # 退出条件
            # if cv2.waitKey(50) == ord('q') or imageNum > fps * end:
            #     break
        self.video.release()
        cv2.destroyAllWindows()



class MZCV(QWidget):

    def __init__(self):
        super(MZCV, self).__init__()
        #全局变量
        self.IMG_PATH=os.path.join(os.path.dirname(__file__),'imgs')
        self.is_started=0#0为没开始，1为开始，-1为暂停
        self.cap_btn_sty=''' 
                      "QPushButton{background-color:#DCDCDC}"
                      "QPushButton{border:2px}"
                      "QPushButton{border-radius:10px}"
                      "QPushButton{padding:2px 4px}"
                      "QPushButton{text-align:bottom }" '''
#"QPushButton{color:black}"
                      #"QPushButton:hover{color:red}"

        # self.is_pause=False
        palette = QPalette()
        palette.setColor(palette.Background, QColor('#FDF5E6'))
        self.setPalette(palette)
        self.setWindowTitle('MZ录屏小工具')
        icon=QIcon()
        icon_path=os.path.join(self.IMG_PATH,'c.png')
        icon.addPixmap(QPixmap(icon_path))
        self.setWindowIcon(icon)
        self.main_layout=QHBoxLayout()



        self.btn_layout=QVBoxLayout()
        self.start_btn=QPushButton('开始录')
        self.start_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                     "QPushButton{border:2px}"
                                     "QPushButton{padding:2px 4px}"
                                     "QPushButton{border-radius:5px}")
        self.start_btn.clicked.connect(self.start_cv)
        self.end_btn=QPushButton('结 束')
        self.end_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                   "QPushButton{border:2px}"
                                   "QPushButton{padding:2px 4px}"
                                   "QPushButton{border-radius:5px}"
                                   "QPushButton:hover{color:red}")

        self.end_btn.clicked.connect(self.end_cv)
        self.btn_layout.addWidget(self.start_btn)
        self.btn_layout.addWidget(self.end_btn)

        self.setting_layout=QVBoxLayout()
        self.fram_layout=QHBoxLayout()
        # self.fram_layout.setAlignment(Qt.AlignLeft)
        self.name_label=QLabel(' 文件名 :')
        self.name_edit=QLineEdit()
        self.name_edit.setText('录屏_1')
        self.auto_series=QCheckBox('自动连续')
        self.auto_series.setChecked(True)
        self.fram_label=QLabel('帧数:')
        self.fram_edit=QLineEdit()
        self.fram_edit.setFixedWidth(50)
        intLimit = QIntValidator(0, 60, self)
        self.fram_edit.setValidator(intLimit)
        self.fram_edit.setText('30')
        self.fram_edit.setAlignment(Qt.AlignLeft)
        self.fram_layout.addWidget(self.name_label)
        self.fram_layout.addWidget(self.name_edit)
        self.fram_layout.addWidget(self.fram_label)
        self.fram_layout.addWidget(self.fram_edit)
        self.fram_layout.addWidget(self.auto_series)
        self.out_layout=QHBoxLayout()
        self.out_label=QLabel('输出目录:')
        self.out_edit=QLineEdit()
        self.out_btn=QPushButton('...')
        self.out_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"                               
                                         "QPushButton{border:2px}"
                                         "QPushButton{padding:2px 4px}"
                                         "QPushButton{border-radius:5px}")#   "QPushButton{color:#32CD32}"
        self.out_btn.setFixedWidth(50)
        self.out_btn.clicked.connect(self.open_dir)
        self.out_layout.addWidget(self.out_label)
        self.out_layout.addWidget(self.out_edit)
        self.out_layout.addWidget(self.out_btn)
        self.setting_layout.addLayout(self.fram_layout)
        self.setting_layout.addLayout(self.out_layout)

        self.main_layout.addLayout(self.btn_layout)
        self.main_layout.addLayout(self.setting_layout)
        self.setLayout(self.main_layout)

        self.timer=QBasicTimer()
        self._cap_thread=CaptureThread()


    #dir=QFileDialog.getExistingDirectory(self,'选择文件夹')
    def start_cv(self):
        v_name=self.name_edit.text()
        fps=int(self.fram_edit.text())
        dir=self.out_edit.text()
        if v_name and fps and dir:
            v_path=os.path.join(dir,v_name+'.mp4')#'.mp4'
            try:
                if self.is_started ==0:#还没开始录屏
                    print('开始录屏')
                    self.start_btn.setText('录制中')
                    # self.start_btn.setStyleSheet('border-radius:10px,color:#32CD32')#	#7FFF00
                    self.start_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                                 "QPushButton{color:#32CD32}"
                                                 "QPushButton{border:2px}"
                                                 "QPushButton{padding:2px 4px}"
                                                 "QPushButton{border-radius:5px}")#"QPushButton{background-color:#32CD32}"
                    self.is_started=1
                    self.time_window=TimeTip()
                    self.time_window.start_Signal.connect(self._start_capture)
                    self.time_window.show()
                    self._cap_thread.setting(fps,v_path)
                    self._cap_thread.setPause(False)
                    # self.timer.start()


                elif self.is_started==1:#已经开始了
                    print('暂停')
                    self.start_btn.setText('暂停中')
                    # self.start_btn.setStyleSheet('color:#FF8C00')#	#7FFF00
                    self.start_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                                 "QPushButton{color:#FF8C00}"
                                                 "QPushButton{border:2px}"
                                                 "QPushButton{padding:2px 4px}"
                                                 "QPushButton{border-radius:5px}")
                    self.is_started=-1
                    self._cap_thread.setPause(True)
                else:#为-1时，表示正在暂停
                    print('继续')
                    self.start_btn.setText('正在录')
                    # self.start_btn.setStyleSheet('color:#32CD32')#	#7FFF00
                    self.start_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                                 "QPushButton{color:#32CD32}"
                                                 "QPushButton{border:2px}"
                                                 "QPushButton{padding:2px 4px}"
                                                 "QPushButton{border-radius:5px}")
                    self.is_started=1
                    self._cap_thread.setPause(False)
            except Exception as start_cv_ERR:
                print('start_cv_ERR错误')
                print(str(start_cv_ERR))
        else:
            QMessageBox.information(self,'提示','请输入完成名称、帧数率以及输出目录')

    def end_cv(self):
        print('结束')
        self.start_btn.setText('开始录')
        # self.start_btn.setStyleSheet('color:#000000')
        self.start_btn.setStyleSheet("QPushButton{background-color:#DCDCDC}"
                                     "QPushButton{border:2px}"
                                     "QPushButton{padding:2px 4px}"
                                     "QPushButton{border-radius:5px}")
        self.is_started=0
        self._cap_thread._stop()

    def _start_capture(self,int_value):
        if int_value==1:
            self._cap_thread.start()


    def open_dir(self):
        dir = QFileDialog.getExistingDirectory(self, '选择目录')
        if dir:
            self.out_edit.setText(dir)


if __name__ == '__main__':
    app=QApplication(sys.argv)
    mz=MZCV()
    mz.show()
    sys.exit(app.exec_())
